package com.muyu.danmo.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muyu.common.core.domain.Result;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.mapper.DanmoOrderItemMapper;
import com.muyu.danmo.mapper.DanmoOrderMapper;
import com.muyu.danmo.mapper.OrderAfterSalesInfoMapper;
import com.muyu.danmo.service.IDanmoOrderService;
import com.muyu.common.core.enums.OrderStatus;
import com.muyu.common.core.enums.PayStatus;
import com.muyu.danmo.utils.JPushUtils;
import com.muyu.remote.RemoteVipPackage;
import com.muyu.remote.RemoteVipPerson;
import com.muyu.system.danmo.dto.PayDTO;
import com.muyu.system.danmo.dto.PaymentCallBackResult;
import com.muyu.system.danmo.fegin.PayFeign;
import com.muyu.system.danmo.vo.PayVO;
import com.muyu.system.danmo.vo.RefundResultServiceVO;
import com.muyu.system.domain.*;
import com.muyu.system.domain.Bo.DanmoOrderBo;
import com.muyu.system.domain.Vo.*;
import com.muyu.system.domain.dto.OrderCountDTO;
import com.muyu.system.domain.dto.OrderListDTO;
import com.muyu.system.domain.dto.StatusCountDTO;
import com.muyu.system.domain.enums.AfterSalesStatusEnum;
import com.muyu.system.domain.enums.JpushMessageEnum;
import com.muyu.system.domain.enums.OrderSourceEnum;
import com.muyu.system.shopping.fegin.SecurityDepositFegin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.muyu.common.core.constant.Constants.MCH_CODE;
import static com.muyu.common.core.constant.CommonConstant.*;

/**
 * 订单Service业务层处理
 *
 * @author yangle
 * @date 2025-01-18
 */
@Service
@Slf4j
public class DanmoOrderServiceImpl implements IDanmoOrderService {
    @Autowired
    private DanmoOrderMapper danmoOrderMapper;
    @Autowired
    private DanmoOrderItemMapper danmoOrderItemMapper;
    @Autowired
    private PayFeign payFeign;

    @Autowired
    private OrderAfterSalesInfoMapper orderAfterSalesInfoMapper;


    @Autowired
    private SecurityDepositFegin securityDepositFegin;

    @Autowired
    private JPushUtils jPushUtils;

    @Autowired
    private RemoteVipPerson remoteVipPerson;

    @Autowired
    private RemoteVipPackage  remoteVipPackage;



    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public DanmoOrderVo selectDanmoOrderById(Long id) {
        DanmoOrder danmoOrder = danmoOrderMapper.selectDanmoOrderById(id);
        DanmoOrderVo danmoOrderVo = BeanUtil.toBean(danmoOrder, DanmoOrderVo.class);
        DanmoOrderItem danmoOrderItem = new DanmoOrderItem();
        danmoOrderItem.setOrderId(danmoOrderVo.getId());
        List<DanmoOrderItem> danmoOrderItemList = danmoOrderItemMapper.selectDanmoOrderItemList(danmoOrderItem);
        danmoOrderVo.setOrderItemList(danmoOrderItemList);
        return danmoOrderVo;
    }

    /**
     * 查询订单列表
     *
     * @param danmoOrder 订单
     * @return 订单
     */
    @Override
    public List<DanmoOrderVo> selectDanmoOrderList(DanmoOrder danmoOrder) {
        List<DanmoOrder> danmoOrderList = danmoOrderMapper.selectDanmoOrderList(danmoOrder);
        List<DanmoOrderVo> danmoOrderVoList = BeanUtil.copyToList(danmoOrderList, DanmoOrderVo.class);
        if (danmoOrderVoList.size() > 0) {
            List<Long> orderIds = danmoOrderVoList.stream().map(DanmoOrderVo::getId).collect(Collectors.toList());
            List<DanmoOrderItem> danmoOrderItemLists = danmoOrderItemMapper.selectDanmoOrderItemListByOrderIds(orderIds);
            Map<Long, List<DanmoOrderItem>> danmoOrderItemMap = danmoOrderItemLists.stream().collect(Collectors.groupingBy(DanmoOrderItem::getOrderId));
            for (DanmoOrderVo danmoOrderVo : danmoOrderVoList) {
                danmoOrderVo.setOrderItemList(danmoOrderItemMap.get(danmoOrderVo.getId()));
            }
        }
        return danmoOrderVoList;
    }

    @Override
    public Result orderCountOfStore(DanmoOrder danmoOrder) {
        List<DanmoOrder> danmoOrderList = danmoOrderMapper.selectDanmoOrderList(danmoOrder);
        Map<String, Integer> countMap = new HashMap<>();
        countMap.put("notPay", danmoOrderList.stream().filter(a -> a.getSellerStatus().equals(0)).collect(Collectors.toList()).size());
        countMap.put("paid", danmoOrderList.stream().filter(a -> a.getSellerStatus().equals(1)).collect(Collectors.toList()).size());
        countMap.put("deliver", danmoOrderList.stream().filter(a -> a.getSellerStatus().equals(2)).collect(Collectors.toList()).size());
        countMap.put("received", danmoOrderList.stream().filter(a -> a.getSellerStatus().equals(3)).collect(Collectors.toList()).size());
        countMap.put("afterSales", danmoOrderList.stream().filter(a -> a.getSellerStatus().equals(4)).collect(Collectors.toList()).size());
        return Result.success(countMap);
    }

    /**
     * 新增订单
     *
     * @param danmoOrderBo 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertDanmoOrder(DanmoOrderBo danmoOrderBo) {
//        if (danmoOrderBo.getSourceType()==1){
        List<DanmoOrderItem> danmoOrderItemList = danmoOrderBo.getOrderItemList();
        //后端计算订单总额是否一致
        BigDecimal totalAmount = new BigDecimal(0);
        for (DanmoOrderItem danmoOrderItem : danmoOrderItemList) {
            BigDecimal skuPrice = danmoOrderMapper.findSkuPrice(danmoOrderItem.getSkuId());
            totalAmount = totalAmount.add(skuPrice.multiply(BigDecimal.valueOf(danmoOrderItem.getSkuQuantity())));
            // 校验规格库存
            Long skuQuantity = danmoOrderItem.getSkuQuantity();
            Integer skuNum = danmoOrderMapper.findSkuNum(danmoOrderItem.getSkuId());
            if(null == skuNum){
                throw new RuntimeException("商品库存不足");
            }
            if((skuNum - skuQuantity) < 0){
                throw new RuntimeException("商品库存不足");
            }
        }
        if (totalAmount.compareTo(danmoOrderBo.getTotalAmount()) != 0) {
            return Result.error("订单金额与商品金额不一致");
        }
        DanmoOrder danmoOrder = BeanUtil.toBean(danmoOrderBo, DanmoOrder.class);
        danmoOrder.setTotalAmount(totalAmount);
        danmoOrder.setCreateTime(DateUtil.date().toLocalDateTime());
        danmoOrder.setOrderSn(ORDER_TOP + RandomUtil.randomNumbers(16));
        // 调用支付
        PayDTO payDTO = new PayDTO();
        payDTO.setProjectName(danmoOrder.getSourceType().getName());
        payDTO.setMchCode(MCH_CODE);
        payDTO.setPayMethod(danmoOrder.getPayType());
        payDTO.setBizOrderNo(danmoOrder.getOrderSn());
        payDTO.setDescription(danmoOrder.getSourceType().getName());
        payDTO.setTotalAmount(danmoOrder.getTotalAmount().multiply(BigDecimal.valueOf(100)).longValue());
        payDTO.setTimeExpire(DateUtil.offsetMinute(DateUtil.date(), 30).toLocalDateTime());
        payDTO.setPayTel(danmoOrderBo.getTel());
        Result<PayVO> pay = payFeign.pay(payDTO);
        if (pay.getCode() != 200) {
            throw new RuntimeException(pay.getMsg());
        }
        danmoOrder.setPayOrderNo(pay.getData().getOrderNo());
        danmoOrderMapper.insertDanmoOrder(danmoOrder);
        Long orderId = danmoOrder.getId();
        danmoOrder.setStatus(OrderStatus.PAY_PENDING);
        for (DanmoOrderItem orderItem : danmoOrderItemList) {
            orderItem.setOrderId(orderId);
            danmoOrderItemMapper.insertDanmoOrderItem(orderItem);
        }
        return Result.success(pay.getData(), "添加成功");
    }

    /**
     * 修改订单
     *
     * @param danmoOrder 订单
     * @return 结果
     */
    @Override
    public Result updateDanmoOrder(DanmoOrder danmoOrder) {
        danmoOrderMapper.updateDanmoOrder(danmoOrder);
        return Result.success(danmoOrder, "修改成功");
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoOrderByIds(Long[] ids) {
        danmoOrderMapper.deleteDanmoOrderByIds(ids);
        return Result.success(ids, "删除成功");
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoOrderById(Long id) {
        danmoOrderMapper.deleteDanmoOrderById(id);
        return Result.success(id, "删除成功");
    }

    @Override
    public void update(PaymentCallBackResult paymentCallBackResult) {
        // 判断时那个业务的订单
        String bizOrderNo = paymentCallBackResult.getBizOrderNo();
        String top = bizOrderNo.split("_")[0];
        if (StrUtil.isEmpty(top)) {
            return;
        }
        switch (top + "_") {
            case ORDER_TOP:
                // 订单业务
                if (paymentCallBackResult.getStatus().equals(PayStatus.SUCCESS)) {
                    new LambdaUpdateChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getOrderSn, bizOrderNo)
                                    .set(DanmoOrder::getStatus, OrderStatus.TO_BE_SHIPPED.getCode())
                                    .set(DanmoOrder::getPaymentTime, paymentCallBackResult.getCompletedTime()).update();
                    // 减少库存
                    DanmoOrder danmoOrder = reduceInventory(bizOrderNo);
                    Long sellerId = danmoOrder.getSellerId();
                    Long userId = danmoOrderMapper.findStoreById(sellerId);
                    // 发送极光
                    jPushUtils.send(userId, JpushMessageEnum.PLACE_ORDER);
                } else {
                    danmoOrderMapper.updateOrder(bizOrderNo, OrderStatus.CLOSE.getCode());
                }
                break;
            case MARKET_TOP:
                // 充值业务
                if (paymentCallBackResult.getStatus().equals(PayStatus.SUCCESS)) {
                    danmoOrderMapper.updateMarketOrderPaymentTime(bizOrderNo, OrderStatus.TO_BE_SHIPPED.getCode(), paymentCallBackResult.getCompletedTime());
                    // 发送极光
                    Long sellerUserId = danmoOrderMapper.findSellerUserIdByBizOrderNo(bizOrderNo);
                    jPushUtils.send(sellerUserId, JpushMessageEnum.PAINTING_PLACE_ORDER);
                } else {
                    danmoOrderMapper.updateMarketOrder(bizOrderNo, OrderStatus.CLOSE.getCode());
                    // 修改书画交易商品的状态
                    danmoOrderMapper.updateMarketProducts(bizOrderNo);
                }
                break;
            case MEMBER_TOP:
                // 充值业务
                danmoOrderMapper.updateMember(bizOrderNo, paymentCallBackResult.getStatus().getCode(),paymentCallBackResult.getCompletedTime() == null ? DateUtil.date().toLocalDateTime() : paymentCallBackResult.getCompletedTime());
                break;
            case SECURITY_DEPOSIT_TOP:
                Result<String> stringResult = securityDepositFegin.payResultsHandle(paymentCallBackResult);
                if (!Result.isSuccess(stringResult)) {
                    log.error(stringResult.getMsg());
                    throw new RuntimeException("处理保证金充值失败！");
                }
                break;
            case VIP_TOP:
                // 获取订单信息
                DanmoVipPerson danmoVipPerson = new DanmoVipPerson();
                danmoVipPerson.setOrderSn(bizOrderNo);
                DanmoVipPerson person = remoteVipPerson.person(danmoVipPerson);
                if (person == null) {
                    log.error("VIP订单不存在: {}", bizOrderNo);
                    throw new RuntimeException("VIP订单不存在");
                }
                // 处理支付状态
                if (paymentCallBackResult.getStatus().equals(PayStatus.SUCCESS)) {
                    // 获取当前用户ID
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    Long userId = loginUser.getUserid();
                    // 计算会员有效期
                    LocalDateTime expireTime = calculateExpireTime(userId);
                    DanmoVipPerson danmoVipPerson1 = new DanmoVipPerson();
                    danmoVipPerson1.setUserId(userId);
                    DanmoVipPerson personed = remoteVipPerson.person(danmoVipPerson);

                        // 更新现有会员
                        personed.setExpirationTime(expireTime);
                        personed.setPayStatus(PayStatus.SUCCESS);
                        personed.setOrderSn(bizOrderNo);
                        personed.setDeleteFlag(0);
                        remoteVipPerson.edit(personed);

//                        // 发送通知
//                        jPushUtils.send(userId, JpushMessageEnum.VIP_UPGRADE_SUCCESS);
                    }

                break;
            case PREMIUM_TOP:
                Result<String> result = securityDepositFegin.premiumPayResults(paymentCallBackResult);
                if (!Result.isSuccess(result)) {
                    log.error(result.getMsg());
                    throw new RuntimeException("处理手续费充值失败！");
                }
                break;
            default:
                throw new RuntimeException("订单业务异常");
        }


    }

    private LocalDateTime calculateExpireTime(Long userId) {
        DanmoVipPerson danmoVipPerson = new DanmoVipPerson();
        danmoVipPerson.setUserId(userId);
        DanmoVipPerson person = remoteVipPerson.person(danmoVipPerson);
        Long vipPackageId = person.getVipPackageId();
        DanmoVipPackage danmoVipPackage = new DanmoVipPackage();
        danmoVipPackage.setId(vipPackageId);
        DanmoVipPackage packages = remoteVipPackage.packages(danmoVipPackage);
        Long months = packages.getMonths();
        if (danmoVipPerson != null && danmoVipPerson.getExpirationTime() != null
                && danmoVipPerson.getExpirationTime().isAfter(LocalDateTime.now())) {
            return months == -1
                    ? LocalDateTime.of(9999, 12, 31, 23, 59, 59)  // 永久会员
                    : danmoVipPerson.getExpirationTime().plusMonths(months);
        } else {
            return months == -1
                    ? LocalDateTime.of(9999, 12, 31, 23, 59, 59)  // 永久会员
                    : LocalDateTime.now().plusMonths(months);
        }
    }

    public static void main(String[] args) {
        String refundBizOrderNo = "refund_market_5786039545278240";
        int secondUnderscoreIndex = refundBizOrderNo.indexOf("_", refundBizOrderNo.indexOf("_") + 1);
        String top = refundBizOrderNo.substring(0, secondUnderscoreIndex + 1);
        System.out.println("1111");
        switch (top) {
            case REFUND_ORDER_TOP:
                System.out.println("3333");
            case REFUND_MARKET_TOP:
                System.out.println("2222");
        }
    }



    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateRefund(RefundResultServiceVO refundResultServiceVO) {
        String refundBizOrderNo = refundResultServiceVO.getRefundBizOrderNo();
        int secondUnderscoreIndex = refundBizOrderNo.indexOf("_", refundBizOrderNo.indexOf("_") + 1);
        String top = refundBizOrderNo.substring(0, secondUnderscoreIndex + 1);
        if (StrUtil.isEmpty(top)) {
            return;
        }
        switch (top) {
            case REFUND_ORDER_TOP:
                DanmoOrder one = new LambdaQueryChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getRefundOrderSn, refundBizOrderNo)
                        .one();
                // 订单业务
                if (refundResultServiceVO.getStatus().equals(PayStatus.SUCCESS)) {
                    // 处理售后的状态
                    if(one.getStatus().equals(OrderStatus.AFTER_SALES)){
                        new LambdaUpdateChainWrapper<>(orderAfterSalesInfoMapper).eq(OrderAfterSalesInfo::getOrderId, one.getId())
                                .set(OrderAfterSalesInfo::getAfterSalesStatus, AfterSalesStatusEnum.REFUND_SUCCESS).update();
                    }
                    new LambdaUpdateChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getRefundOrderSn, refundBizOrderNo)
                            .set(DanmoOrder::getStatus, OrderStatus.REFUND_SUCCESS)
                            .set(DanmoOrder::getRefundTime, refundResultServiceVO.getCompletedTime())
                            .update();
                    addInventory(refundBizOrderNo);
                } else {
                    // 处理售后的状态
                    if(one.getStatus().equals(OrderStatus.AFTER_SALES)){
                        new LambdaUpdateChainWrapper<>(orderAfterSalesInfoMapper).eq(OrderAfterSalesInfo::getOrderId, one.getId())
                                .set(OrderAfterSalesInfo::getAfterSalesStatus, AfterSalesStatusEnum.REFUND_FAIL).update();
                    }
                    new LambdaUpdateChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getRefundOrderSn, refundBizOrderNo)
                            .set(DanmoOrder::getStatus, OrderStatus.REFUND_FAILED).update();
                }
                break;
            case REFUND_MARKET_TOP:
                Long id = danmoOrderMapper.findIdByRefundOrderSn(refundBizOrderNo);
                Integer marketOrderStatus = danmoOrderMapper.findMarketOrderStatusByPayId(id);
                OrderStatus orderStatus = OrderStatus.getByCode(marketOrderStatus);
                // 充值业务
                if (refundResultServiceVO.getStatus().equals(PayStatus.SUCCESS)) {
                    // 处理售后的状态
                    if(orderStatus.equals(OrderStatus.AFTER_SALES)){
                        new LambdaUpdateChainWrapper<>(orderAfterSalesInfoMapper).eq(OrderAfterSalesInfo::getOrderId, id)
                                .set(OrderAfterSalesInfo::getAfterSalesStatus, AfterSalesStatusEnum.REFUND_SUCCESS).update();
                    }
                    danmoOrderMapper.updateMarketRefundOrder(refundBizOrderNo, OrderStatus.REFUND_SUCCESS.getCode(), refundResultServiceVO.getCompletedTime());
                } else {
                    // 处理售后的状态
                    if(orderStatus.equals(OrderStatus.AFTER_SALES)){
                        new LambdaUpdateChainWrapper<>(orderAfterSalesInfoMapper).eq(OrderAfterSalesInfo::getOrderId, id)
                                .set(OrderAfterSalesInfo::getAfterSalesStatus, AfterSalesStatusEnum.REFUND_FAIL).update();
                    }else {
                        Long marketProductsId = danmoOrderMapper.findMarketProductsByRefundOrderSn(refundBizOrderNo);
                        danmoOrderMapper.updateMarketProductsById(marketProductsId);
                    }
                    danmoOrderMapper.updateMarketRefundOrder(refundBizOrderNo, OrderStatus.REFUND_FAILED.getCode(),null);
                }
                break;
            case REFUND_SECURITY_DEPOSIT_TOP:
                Result<String> stringResult = securityDepositFegin.refundResultsHandle(refundResultServiceVO);
                if (!Result.isSuccess(stringResult)) {
                    log.error(stringResult.getMsg());
                    throw new RuntimeException("处理保证金退款失败！");
                }
                break;
            default:
                throw new RuntimeException("订单业务异常");
        }

    }

    /**
     * 减少库存
     * @param bizOrderNo
     */
    public DanmoOrder reduceInventory(String bizOrderNo){
        DanmoOrder order = new LambdaQueryChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getOrderSn, bizOrderNo)
                .select(DanmoOrder::getId,  DanmoOrder::getSellerId).one();
        if(null == order){
            throw new RuntimeException("订单不存在");
        }
        List<DanmoOrderItem> list = new LambdaQueryChainWrapper<>(danmoOrderItemMapper)
                .eq(DanmoOrderItem::getOrderId, order.getId())
                .select(DanmoOrderItem::getSkuId,DanmoOrderItem::getSkuQuantity).list();
        list.forEach(a ->{
            Long skuQuantity = a.getSkuQuantity();
            // 获取当前商品规格的库存
            Integer skuNum = danmoOrderMapper.findSkuNum(a.getSkuId());
            int i = (int) (skuNum - skuQuantity);
            danmoOrderMapper.updateSkuNum(a.getSkuId(), i);
            if(i == 0){
                Long sellerId = order.getSellerId();
                Long userId = danmoOrderMapper.findStoreById(sellerId);
                jPushUtils.send(userId,JpushMessageEnum.INVENTORY_ALERTS);
            }
        });
        return order;
    }

    /**
     * 增加库存
     * @param refundBizOrderNo
     */
    public void addInventory(String refundBizOrderNo){
        DanmoOrder order = new LambdaQueryChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getRefundOrderSn, refundBizOrderNo)
                .select(DanmoOrder::getId).one();
        if(null == order){
            throw new RuntimeException("订单不存在");
        }
        List<DanmoOrderItem> list = new LambdaQueryChainWrapper<>(danmoOrderItemMapper)
                .eq(DanmoOrderItem::getOrderId, order.getId())
                .select(DanmoOrderItem::getSkuId,DanmoOrderItem::getSkuQuantity)
                .list();
        list.forEach(a ->{
            Long skuQuantity = a.getSkuQuantity();
            // 获取当前商品规格的库存
            Integer skuNum = danmoOrderMapper.findSkuNum(a.getSkuId());
            danmoOrderMapper.updateSkuNum(a.getSkuId(), (int) (skuNum + skuQuantity));
        });
    }

    @Override
    public IPage<OrderListVO> orderList(OrderListDTO orderListDTO) {
        IPage<OrderListVO> orderListVOIPage = danmoOrderMapper.orderList(new Page<>(orderListDTO.getPageNum(), orderListDTO.getPageSize()),
                orderListDTO.getStatus() == null ? null :orderListDTO.getStatus().getCode(),null,
                orderListDTO.getSource() == null ? null :orderListDTO.getSource().getCode(),
                orderListDTO.getStoreId() == null ? null :orderListDTO.getStoreId(),
                orderListDTO.getUserId() == null ? null :orderListDTO.getUserId());
        orderListVOIPage.getRecords().stream().filter(a -> a.getSource().equals(OrderSourceEnum.ORDER)).forEach(b ->{
            // 单独处理商户的订单，因为是多个商品
            List<OrderItemVO> orderItemVOS = danmoOrderMapper.orderListItem(b.getId());
            b.setOrderItemList(orderItemVOS);
        });
        return orderListVOIPage;
    }

    @Override
    public OrderListVO findByOrderSn(String orderSn) {
        IPage<OrderListVO> orderListVOIPage = danmoOrderMapper.orderList(new Page<>(1, 10), null,orderSn,null,null,null);
        orderListVOIPage.getRecords().stream().filter(a -> a.getSource().equals(OrderSourceEnum.ORDER)).forEach(b ->{
            // 单独处理商户的订单，因为是多个商品
            List<OrderItemVO> orderItemVOS = danmoOrderMapper.orderListItem(b.getId());
            b.setOrderItemList(orderItemVOS);
        });
        return orderListVOIPage.getRecords().get(0);
    }

    @Override
    public OrderCountVO count(OrderCountDTO orderCountDTO) {
        OrderCountVO orderCountVO = new OrderCountVO();
        List<DanmoOrder> list = new LambdaQueryChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getSellerId, orderCountDTO.getStoreId())
                .ge(DanmoOrder::getCreateTime, DateUtil.beginOfDay(new Date()))
                .le(DanmoOrder::getCreateTime, DateUtil.endOfDay(new Date()))
                .select(DanmoOrder::getId, DanmoOrder::getTotalAmount).list();
        orderCountVO.setDayCount(list.size());
        BigDecimal reduce = list.stream().filter(a -> a.getStatus().equals(OrderStatus.SUCCESS)).map(DanmoOrder::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderCountVO.setDayAmount(reduce);

        List<DanmoOrder> yesterdaylist = new LambdaQueryChainWrapper<>(danmoOrderMapper).eq(DanmoOrder::getSellerId, orderCountDTO.getStoreId())
                .ge(DanmoOrder::getCreateTime, DateUtil.beginOfDay(DateUtil.yesterday()))
                .le(DanmoOrder::getCreateTime, DateUtil.endOfDay(DateUtil.yesterday()))
                .select(DanmoOrder::getId, DanmoOrder::getTotalAmount).list();
        orderCountVO.setYesterdayCount(yesterdaylist.size());
        BigDecimal yesterdayReduce = yesterdaylist.stream().filter(a -> a.getStatus().equals(OrderStatus.SUCCESS)).map(DanmoOrder::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderCountVO.setYesterdayAmount(yesterdayReduce);
        return orderCountVO;
    }

    @Override
    public StatusCountVO statusCount(StatusCountDTO statusCountDTO) {
        StatusCountVO statusCountVO = new StatusCountVO();
        List<DanmoOrder> list = new LambdaQueryChainWrapper<>(danmoOrderMapper)
                .eq(DanmoOrder::getSellerId, statusCountDTO.getStoreId())
                .isNotNull(DanmoOrder::getStatus)
                .select(DanmoOrder::getId, DanmoOrder::getStatus).list();
        Map<OrderStatus, List<DanmoOrder>> collect = list.stream().collect(Collectors.groupingBy(DanmoOrder::getStatus));
        statusCountVO.setShippedCount(collect.get(OrderStatus.TO_BE_SHIPPED) == null  ? 0 : collect.get(OrderStatus.TO_BE_SHIPPED).size());
        statusCountVO.setAfterSalesCount(collect.get(OrderStatus.AFTER_SALES) == null  ? 0 : collect.get(OrderStatus.AFTER_SALES).size());
        statusCountVO.setRejectedCount(collect.get(OrderStatus.REJECTED) == null  ? 0 : collect.get(OrderStatus.REJECTED).size());
        statusCountVO.setRefundSuccessCount(collect.get(OrderStatus.REFUND_SUCCESS) == null  ? 0 : collect.get(OrderStatus.REFUND_SUCCESS).size());
        statusCountVO.setSuccessCount(collect.get(OrderStatus.SUCCESS) == null  ? 0 : collect.get(OrderStatus.SUCCESS).size());
        return statusCountVO;
    }
}
